package com.blog.backend.exception;

import com.blog.backend.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;


/**
 * 异常处理类
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(Exception e) {
        String message="请联系管理员";
        log.error(getExceptionInfo(e));
        if (e instanceof MethodArgumentNotValidException){
           message= ((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage();
        }
        return Result.failure(null,message,500);
    }

    @ExceptionHandler(GlobalException.class)
    @ResponseBody
    public Result error(GlobalException e) {
        // EduException e1 = new EduException(20001,"自定义异常测试，操作失败......";
        log.info("自定义业务异常:" + e.getMessage());
        return Result.failure(null,e.getMessage(),e.getCode());
    }

    private static String getExceptionInfo(Exception ex) {
        StackTraceElement[] stackTrace = ex.getStackTrace();
        StringBuffer sb = new StringBuffer();
        sb.append(ex.toString()).append("\r\n");
        for (StackTraceElement stackTraceElement : stackTrace) {
            sb.append("\tat ").append(stackTraceElement.getClassName()).append(".")
                    .append(stackTraceElement.getMethodName())
                    .append("(").append(stackTraceElement.getFileName()).append(":").append(stackTraceElement.getLineNumber())
                    .append(")\r\n");
        }
        return sb.toString();
    }

}
